﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RootBaseFramework.Domain;
using TestRootBaseData.Service.Model;
using TestRootBaseData.Service.Repository.Database;

namespace TestRootBaseData.Service
{
  public  class ServiceManager
    {

        RootBaseTestContext _MyContext;

        public RootBaseTestContext MyContext
        {
            get
            {
                if (_MyContext == null)
                    _MyContext = new RootBaseTestContext();

                return _MyContext;
            }
            //set { _MyContext = value; }
        }

        private RootBaseFramework.Infra.Data.UnitOfWork _uWork;

        public RootBaseFramework.Infra.Data.UnitOfWork UWork
        {
            get
            {
                if (_uWork == null)
                    _uWork = new RootBaseFramework.Infra.Data.UnitOfWork(MyContext);
                return _uWork;
            }
          //  set { _uWork = value; }
        }

        private PersonRepository _personRepo;

        public PersonRepository PersonRepo
        {
            get
            {
                if (_personRepo == null)
                {
                    _personRepo = new PersonRepository(UWork);
                }
                return _personRepo; 
            }
           // set { _personRepo = value; }
        }


        #region CRUD
        public void ClearPeople()
        {
            var q = GetPeople();
            //q.Clear();

            foreach( Person p in q)
            {
                if (p.ParentId == null)
                {
                    PersonRepo.Remove(p);
                }
                else
                {
                    p.ParentId = null;
                    UWork.Commit();
                    PersonRepo.Remove(p);
                }


            }


          

            UWork.Commit();
        }

        public  List<Person> GetPeople()
      {
          return PersonRepo.FindAll().ToList();
      }

        public Person GetPerson(int personId)
        {
            var p = PersonRepo.Find(personId);
            return p;
        }

      public Person MakeChild(Person parent,Person child)
      {
          child.Parent = parent;
          UWork.Commit();
          return child;

      }

        public List<Person> Populate()
        {
            for (int i = 0; i < 10; ++i)
            {
                var p = new Person
                {
                    FirstName = "MOnde"+ i.ToString() ,
                    LastName = "Galvez"
                    
                };


                PersonRepo.Add(p);
                UWork.Commit();
                p.TraceBloodLine();
                UWork.Commit();
          


            }

          
            return GetPeople();

        }
        #endregion


    }
}
